package com.lhy.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lhy.domain.Chat;
import com.lhy.domain.Friend;
import com.lhy.domain.Result;
import com.lhy.domain.Student;
import com.lhy.service.IUserService;

@Controller
@RequestMapping("/chat")
public class ChatController {
	@Autowired
	private IUserService userService;

	@RequestMapping("")
	public String toIndex(HttpServletRequest request, Model model){
		return "chat";
	}
	@RequestMapping("/do")
	public @ResponseBody
	Map<String, Object> chat(String usersequence, String sequence){
		Map<String, Object> returnMap = new HashMap<>();
		Result result=new Result();
		result.setCode("1");
		result.setDes("成功");
		List <Chat> chats =new ArrayList<>();
		try{
			Integer userSequence = Integer.valueOf(usersequence);
			Integer seQuence = Integer.valueOf(sequence);
			if(userSequence >= seQuence){
				chats = userService.queryMessageBySequence(seQuence,userSequence);
			}else{
				chats = userService.queryMessageBySequence(userSequence,seQuence);
			}
			returnMap.put("chats", chats);
		}catch(Exception e){
			result.setCode("0");
			result.setDes(e.getMessage());
		}
		returnMap.put("result", result);
		return returnMap;
		
	}
	
	@RequestMapping("/send")
	public @ResponseBody
	Map<String, Object> sendMessage(String message, String usersequence, String sequence){
		Map<String, Object> returnMap = new HashMap<>();
		Result result=new Result();
		result.setCode("1");
		result.setDes("成功");
		try{
			Integer userSequence = Integer.valueOf(usersequence);
			Integer seQuence = Integer.valueOf(sequence);
			Integer count1 = userSequence;
			Integer count2 = seQuence;
			Date date = new Date();       
			Timestamp create_dt = new Timestamp(date.getTime());
			Student m = userService.queryStudentBySequence(userSequence);
			Student u = userService.queryStudentBySequence(seQuence);
			String remark = u.getNickname();
			String nickname = m.getNickname();
			if(count1 >= count2){
				userService.insertChatMessage(count2,count1,userSequence,seQuence,nickname,remark,create_dt,message);
			}else{
				userService.insertChatMessage(count1,count2,userSequence,seQuence,nickname,remark,create_dt,message);
			}
		}catch(Exception e){
			result.setCode("0");
			result.setDes(e.getMessage());
		}
		returnMap.put("result", result);
		return returnMap;
	}
}
